#define _CRT_SECURE_NO_WARNINGS 1
#include"SL.h"

void SLIsfull(ST* s)
{
	if (s->size == s->capacity)
	{
		int newcapacity = s->capacity == 0 ? 4 : 2 * s->capacity;
		SLtype* tmp = (SLtype*)realloc(s->a, sizeof(SLtype) * newcapacity);
		if (tmp == NULL)
		{
			printf("realloc failure\n");
			exit(-1);
		}
		s->a = tmp;
		s->capacity = newcapacity;
	}
}

void SLPrint(const ST* s)
{
	int i = 0;
	for (i = 0; i < s->size; i++)
	{
		printf("%d ", s->a[i]);
	}
	printf("\n");
}

void SLInit(ST* s)
{
	s->a = NULL;
	s->size = s->capacity = 0;
}

void SLPushBack(ST* s, SLtype x)
{
	SLIsfull(s);
	s->a[s->size] = x;
	s->size++;
}

void SLPopBack(ST* s)
{
	assert(s->size > 0);
	s->size--;
}

void SLPushFront(ST* s, SLtype x)
{
	SLIsfull(s);
	int end = s->size;
	while (end >0)
	{
		s->a[end] = s->a[end - 1];
		end--;
	}
	s->a[end] = x;
	s->size++;
}

void SLPopFront(ST* s)
{
	assert(s->size > 0);
	int first = 0;
	while (first<s->size-1)
	{
		s->a[first] = s->a[first + 1];
		first++;
	}
	s->size--;
}

void SLDestory(ST* s)
{
	free(s->a);
	s->a = NULL;
	s->size = s->capacity = 0;
}

int SLFind(ST* s, SLtype x)
{
	int i = 0;
	for (i = 0; i < s->size; i++)
	{
		if (s->a[i] == x)
			return i;
	}
	return -1;
}

void SLInsert(ST* s, int pos, SLtype x)
{
	SLIsfull(s);
	if (pos >= s->size)
	{
		SLPushBack(s, x);
	}
	else if (pos < 0)
	{
		SLPushFront(s, x);
	}
	else
	{
		int end = s->size;
		while (end > pos)
		{
			s->a[end] = s->a[end - 1];
			end--;
		}
		s->a[end] = x;
	}
	s->size++;
}

void SLErase(ST* s, int pos)
{
	assert(s->size > 0);
	if (pos >= s->size)
	{
		SLPopBack(s);
	}
	else if (pos < 0)
	{
		SLPopFront(s);
	}
	else
	{
		while (pos < s->size-1)
		{
			s->a[pos] = s->a[pos + 1];
			++pos;
		}
	}
	s->size--;
}